﻿using my.abp.Domain.IManagers.Role;
using my.abp.Domain.Repositories.Role;
using my.abp.Domain.Shared.Entities;
using my.abp.Domain.Shared.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Domain.Services;
using Volo.Abp.Uow;

namespace my.abp.Domain.Managers.Role
{
	public class SysRoleOrgManager : DomainService, ISysRoleOrgManager
	{
		private readonly ISysRoleOrgRepository _sysRoleOrgRep;

		public SysRoleOrgManager(ISysRoleOrgRepository sysUserRoleRep)
		{
			_sysRoleOrgRep = sysUserRoleRep;
		}

		/// <summary>
		/// 根据角色Id集合获取角色机构Id集合
		/// </summary>
		/// <param name="roleIdList"></param>
		/// <returns></returns>
		public async Task<List<long>> GetRoleOrgIdList(List<long> roleIdList)
		{
			var queryable = await _sysRoleOrgRep.AsQueryable();
			return await queryable.Where(u => roleIdList.Contains(u.RoleId))
				.Select(u => u.OrgId).ToListAsync();
		}

		/// <summary>
		/// 根据角色Id删除角色机构
		/// </summary>
		/// <param name="roleId"></param>
		/// <returns></returns>
		public async Task DeleteRoleOrgByRoleId(long roleId)
		{
			await _sysRoleOrgRep.DeleteAsync(u => u.RoleId == roleId);
		}

		/// <summary>
		/// 授权角色机构
		/// </summary>
		/// <param name="input"></param>
		/// <returns></returns>
		[UnitOfWork]
		public async Task GrantRoleOrg(long Id, int DataScope, List<long> OrgIdList)
		{
			await _sysRoleOrgRep.DeleteAsync(u => u.RoleId == Id);
			if (DataScope == (int)DataScopeEnum.Define)
			{
				var roleOrgs = OrgIdList.Select(u => new SysRoleOrg
				{
					RoleId = Id,
					OrgId = u
				}).ToList();
				await _sysRoleOrgRep.InsertRangeAsync(roleOrgs);
			}
		}
	}
}
